package com.black.utils.file.image.code;

import com.black.utils.file.FileTypeEnum;
import com.black.utils.random.RandomUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 验证码工具类，用于生成随机验证码图片和验证码字符串。
 * Verification code utility class for generating random verification code images and strings.
 */
public class VerifyCodeUtil {
    //使用到Algerian字体，系统里没有的话需要安装字体，字体只显示大写，去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";

    /**
     * 使用系统默认字符源生成验证码
     *
     * @param verifySize 验证码长度
     *                   Verification code length.
     * @return 验证码
     * Verification code string.
     * Generate verification code using default character source.
     */
    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     *                   Verification code length.
     * @param sources    验证码字符源
     *                   Verification code character source.
     * @return 验证码
     * Verification code string.
     * Generate verification code using specified character source.
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.isEmpty()) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(RandomUtil.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成随机验证码图片文件,并返回验证码值
     * Generate a random verification code image file and return the verification code string.
     *
     * @param w          图片宽度
     *                   Width of the image.
     * @param h          图片高度
     *                   Height of the image.
     * @param outputFile 图片文件
     *                   Image file.
     * @param verifySize 长度
     *                   Length of the verification code.
     * @return 验证码值
     * Verification code string.
     * @throws IOException IO异常
     *                     IOException
     *                     If an IO error occurs.
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 输出随机验证码图片流,并返回验证码值
     * Output a stream of random verification code images and return the verification code string.
     *
     * @param w          图片宽度
     *                   Width of the image.
     * @param h          图片高度
     *                   Height of the image.
     * @param os         输出流
     *                   Output stream.
     * @param verifySize 长度
     *                   Length of the verification code.
     * @return 验证码值
     * Verification code string.
     * @throws IOException IO异常
     *                     IOException
     *                     If an IO error occurs.
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定验证码图像文件
     * Generate a specified verification code image file.
     *
     * @param w          图片宽度
     *                   Width of the image.
     * @param h          图片高度
     *                   Height of the image.
     * @param outputFile 图片文件
     *                   Image file.
     * @param code       验证码
     *                   Verification code.
     * @throws IOException IO异常
     *                     IOException
     *                     If an IO error occurs.
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
        if (outputFile == null) {
            return;
        }
        File dir = outputFile.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch (IOException e) {
            throw e;
        }
    }

    /**
     * 输出指定验证码图片流
     * Output a specified verification code image stream.
     *
     * @param w    图片宽度
     *             Width of the image.
     * @param h    图片高度
     *             Height of the image.
     * @param os   输出流
     *             Output stream.
     * @param code 验证码
     *             Verification code.
     * @throws IOException IO异常
     *                     IOException
     *                     If an IO error occurs.
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = RandomUtil.nextColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h - 4);

        //绘制干扰线
        g2.setColor(RandomUtil.nextColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = RandomUtil.nextInt(w - 1);
            int y = RandomUtil.nextInt(h - 1);
            int xl = RandomUtil.nextInt(1, 6);
            int yl = RandomUtil.nextInt(1, 12);
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawRate = 0.05f;// 噪声率
        int area = (int) (yawRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = RandomUtil.nextInt(w - 1);
            int y = RandomUtil.nextInt(h - 1);
            int rgb = RandomUtil.getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(RandomUtil.nextColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Serif", Font.ITALIC, fontSize);
        font.deriveFont(Font.PLAIN);
        g2.setFont(font);
        //绘制验证码字符
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            //平移旋转变换类
            AffineTransform affine = new AffineTransform();
            //弧度制角度变换 theta 弧度制角度 在π/4以内随机小数倍数 随机正反反向旋转   旋转中心 x 横坐标中心店 宽度除以字长乘以个数加上一半字体  y纵坐标中心 高/2
            affine.setToRotation(Math.PI / 4 * RandomUtil.nextDouble() * (RandomUtil.nextBoolean() ? 1 : -1), ((double) w / verifySize) * i + (fontSize >> 1), h >> 1);
            //应用该变化
            g2.setTransform(affine);
            //g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
            g2.drawString(String.valueOf(chars[i]), ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }
        g2.dispose();
        ImageIO.write(image, FileTypeEnum.PNG.getExtension(), os);
    }

    /**
     * 扭曲图像，同时在水平和垂直方向进行扭曲。
     * Shear the image both horizontally and vertically.
     *
     * @param g     图形对象，用于绘制扭曲。
     *              Graphics object used for drawing the shear.
     * @param w1    图像宽度。
     *              Width of the image.
     * @param h1    图像高度。
     *              Height of the image.
     * @param color 扭曲时使用的颜色。
     *              Color used during shearing.
     */
    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    /**
     * 在水平方向扭曲图像。
     * Shear the image horizontally.
     *
     * @param g     图形对象，用于绘制扭曲。
     *              Graphics object used for drawing the shear.
     * @param w1    图像宽度。
     *              Width of the image.
     * @param h1    图像高度。
     *              Height of the image.
     * @param color 扭曲时使用的颜色。
     *              Color used during shearing.
     */
    private static void shearX(Graphics g, int w1, int h1, Color color) {
        int period = RandomUtil.nextInt(1);
        int frames = 1;
        int phase = RandomUtil.nextInt(1);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            g.setColor(color);
            g.drawLine((int) d, i, 0, i);
            g.drawLine((int) d + w1, i, w1, i);
        }
    }

    /**
     * 在垂直方向扭曲图像。
     * Shear the image vertically.
     *
     * @param g     图形对象，用于绘制扭曲。
     *              Graphics object used for drawing the shear.
     * @param w1    图像宽度。
     *              Width of the image.
     * @param h1    图像高度。
     *              Height of the image.
     * @param color 扭曲时使用的颜色。
     *              Color used during shearing.
     */
    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = RandomUtil.nextInt(10, 50); // 50;

        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            g.setColor(color);
            g.drawLine(i, (int) d, i, 0);
            g.drawLine(i, (int) d + h1, i, h1);

        }
    }
}
